<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 智能聊天</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- 添加 Marked.js 用于 Markdown 解析 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.3.0/marked.min.js"></script>
    <!-- 添加 highlight.js 用于代码高亮 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/github.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js"></script>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', 'Arial', sans-serif;
        }

        html, body {
            width: 100%;
            height: 100%;
        }

        body {
            background: #f5f7fa;
            color: #333;
            line-height: 1.6;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .chat-container {
            display: flex;
            height: 100vh;
            width: 100%;
            box-shadow: 0 5px 25px rgba(0, 0, 0, 0.1);
        }

        .sidebar {
            width: 250px;
            background: #202123;
            color: white;
            padding: 20px;
            display: flex;
            flex-direction: column;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 30px;
            font-weight: bold;
            font-size: 20px;
        }

        .logo i {
            color: #10a37f;
        }

        .sidebar-section {
            margin-bottom: 20px;
        }

        .sidebar-title {
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 10px;
            color: #8e8ea0;
        }

        .sidebar-option {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 0;
            color: #ececf1;
            cursor: pointer;
            transition: all 0.2s;
        }

        .sidebar-option:hover {
            color: #fff;
        }

        .sidebar-option select {
            background: #3a3b3c;
            color: white;
            border: none;
            padding: 5px;
            border-radius: 4px;
            width: 100%;
        }

        .sidebar-option input[type="text"] {
            background: #3a3b3c;
            color: white;
            border: none;
            padding: 8px;
            border-radius: 4px;
            width: 100%;
        }

        .sidebar-option input[type="text"]::placeholder {
            color: #8e8ea0;
        }

        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: white;
        }

        .chat-area {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        }

        .message {
            display: flex;
            margin-bottom: 20px;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .message-avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
            flex-shrink: 0;
        }

        .message-avatar.user {
            background: #10a37f;
            color: white;
        }

        .message-avatar.ai {
            background: #9d5cff;
            color: white;
        }

        .message-content {
            padding: 10px 15px;
            border-radius: 8px;
            max-width: 80%;
            word-wrap: break-word;
        }

        /* Markdown 样式 */
        .message-content pre {
            background: #f4f4f4;
            border-radius: 4px;
            padding: 10px;
            overflow-x: auto;
            margin: 10px 0;
        }

        .message-content code {
            font-family: 'Courier New', Courier, monospace;
        }

        .message-content p {
            margin-bottom: 10px;
        }

        .message-content h1, 
        .message-content h2, 
        .message-content h3, 
        .message-content h4 {
            margin-top: 15px;
            margin-bottom: 10px;
        }

        .message-content ul, 
        .message-content ol {
            margin-left: 20px;
            margin-bottom: 10px;
        }

        .message-content table {
            border-collapse: collapse;
            margin: 10px 0;
        }

        .message-content th, 
        .message-content td {
            border: 1px solid #ddd;
            padding: 8px;
        }

        .message-content blockquote {
            border-left: 4px solid #ddd;
            padding-left: 10px;
            color: #666;
            margin: 10px 0;
        }

        .user-message .message-content {
            background: #f0f2f5;
        }

        .ai-message .message-content {
            background: #f9f9fb;
            border: 1px solid #e6e6e6;
        }

        .welcome-message {
            text-align: center;
            color: #8e8ea0;
            margin: auto;
            max-width: 600px;
        }

        .welcome-message h1 {
            font-size: 2rem;
            margin-bottom: 20px;
            color: #444;
        }

        .welcome-message p {
            margin-bottom: 30px;
        }

        .input-area {
            padding: 15px 20px;
            border-top: 1px solid #e6e6e6;
            background: white;
            position: relative;
        }

        .input-container {
            position: relative;
            display: flex;
            align-items: flex-end;
        }

        .message-input {
            flex: 1;
            padding: 12px 50px 12px 15px;
            border: 1px solid #e6e6e6;
            border-radius: 8px;
            font-size: 16px;
            line-height: 1.4;
            resize: none;
            max-height: 200px;
            min-height: 24px;
            overflow-y: auto;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        }

        .message-input:focus {
            outline: none;
            border-color: #10a37f;
        }

        .send-button {
            position: absolute;
            right: 10px;
            bottom: 10px;
            background: #10a37f;
            color: white;
            border: none;
            border-radius: 4px;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
        }

        .send-button:hover {
            background: #0d8c6d;
        }

        .send-button:disabled {
            background: #d1d5db;
            cursor: not-allowed;
        }

        .input-options {
            display: flex;
            gap: 15px;
            margin-top: 10px;
            align-items: center;
            font-size: 14px;
            color: #666;
        }

        .input-option {
            display: flex;
            align-items: center;
            gap: 5px;
            cursor: pointer;
        }

        .input-option input[type="checkbox"] {
            cursor: pointer;
        }

        .loading {
            display: inline-block;
            width: 15px;
            height: 15px;
            border: 2px solid #10a37f;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .typing-indicator {
            display: inline-flex;
            align-items: center;
            padding: 8px 12px;
            background: #f0f0f0;
            border-radius: 10px;
            margin-bottom: 10px;
        }

        .typing-indicator span {
            height: 8px;
            width: 8px;
            background-color: #9d5cff;
            border-radius: 50%;
            display: inline-block;
            margin: 0 2px;
            animation: bounce 1.5s infinite ease-in-out;
        }

        .typing-indicator span:nth-child(2) {
            animation-delay: 0.2s;
        }

        .typing-indicator span:nth-child(3) {
            animation-delay: 0.4s;
        }

        @keyframes bounce {
            0%, 80%, 100% { transform: translateY(0); }
            40% { transform: translateY(-5px); }
        }

        /* Mobile responsive */
        @media (max-width: 768px) {
            .chat-container {
                flex-direction: column;
                height: 100vh;
            }
            
            .sidebar {
                width: 100%;
                min-height: auto;
                padding: 15px;
            }
            
            .main-content {
                height: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="sidebar">
            <div class="logo">
                <i class="fa-solid fa-robot"></i>
                <span>AI 智能聊天</span>
            </div>

            <div class="sidebar-section">
                <div class="sidebar-title">模型选择</div>
                <div class="sidebar-option">
                    <select id="modelSelect">
                        <option value="qwen-plus">Qwen-Plus</option>
                        <option value="qwen-max">Qwen-Max</option>
                        <option value="qwen-turbo">Qwen-Turbo</option>
                    </select>
                </div>
            </div>
            <div class="sidebar-section">
                <div class="sidebar-title">接口选择</div>
                <div class="sidebar-option">
                    <select id="urlSelect">
                        <option value="http://localhost:8000/llm/chat">基础聊天接口</option>
                        <option value="http://localhost:8000/llm/chatPlus">增强版聊天接口</option>
                    </select>
                </div>
            </div>
            <div class="sidebar-section">
                <div class="sidebar-title">会话设置</div>
                <div class="sidebar-option">
                    <input type="text" id="sessionIdInput" placeholder="Session ID（默认：1）">
                </div>
                <div class="sidebar-option">
                    <input type="text" id="knowledgeBaseIdInput" placeholder="知识库ID（默认：1）">
                </div>
            </div>
        </div>

        <div class="main-content">
            <div class="chat-area" id="chatArea">
                <div class="welcome-message">
                    <h1>欢迎使用 AI 智能聊天</h1>
                    <p>您可以向 AI 助手询问任何问题，它会尽力为您提供帮助。</p>
                </div>
            </div>

            <div class="input-area">
                <div class="input-container">
                    <textarea class="message-input" id="query" placeholder="输入您的问题..." rows="1"></textarea>
                    <button class="send-button" id="sendButton">
                        <i class="fa-solid fa-paper-plane"></i>
                    </button>
                </div>
                <div class="input-options">
                    <div class="input-option">
                        <input type="checkbox" id="streamCheck" checked>
                        <label for="streamCheck">流式响应</label>
                    </div>
                    <div class="input-option">
                        <input type="checkbox" id="knowledgeEnhanced">
                        <label for="knowledgeEnhanced">知识增强</label>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 初始化 marked.js 解析器配置
        marked.setOptions({
            renderer: new marked.Renderer(),
            highlight: function(code, language) {
                const validLanguage = hljs.getLanguage(language) ? language : 'plaintext';
                return hljs.highlight(code, { language: validLanguage }).value;
            },
            pedantic: false,
            gfm: true,
            breaks: true,
            sanitize: false,
            smartypants: false,
            xhtml: false
        });

        // 自动调整文本框高度
        const textarea = document.getElementById('query');
        textarea.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });

        // 添加消息到聊天区域
        function addMessage(text, isUser = false) {
            const chatArea = document.getElementById('chatArea');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
            
            const avatarDiv = document.createElement('div');
            avatarDiv.className = `message-avatar ${isUser ? 'user' : 'ai'}`;
            avatarDiv.innerHTML = isUser ? '<i class="fa-solid fa-user"></i>' : '<i class="fa-solid fa-robot"></i>';
            
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            
            // 用户消息显示原文，AI消息使用Markdown解析
            if (isUser) {
                contentDiv.textContent = text;
            } else {
                contentDiv.innerHTML = marked.parse(text);
                // 应用代码高亮
                contentDiv.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightElement(block);
                });
            }
            
            messageDiv.appendChild(avatarDiv);
            messageDiv.appendChild(contentDiv);
            chatArea.appendChild(messageDiv);
            
            // 滚动到底部
            chatArea.scrollTop = chatArea.scrollHeight;
            return contentDiv;
        }

        // 显示正在输入指示器
        function showTypingIndicator() {
            const chatArea = document.getElementById('chatArea');
            const indicator = document.createElement('div');
            indicator.className = 'typing-indicator';
            indicator.id = 'typingIndicator';
            indicator.innerHTML = '<span></span><span></span><span></span>';
            chatArea.appendChild(indicator);
            chatArea.scrollTop = chatArea.scrollHeight;
        }

        // 隐藏正在输入指示器
        function hideTypingIndicator() {
            const indicator = document.getElementById('typingIndicator');
            if (indicator) {
                indicator.remove();
            }
        }

        // 表单提交处理
        document.getElementById('sendButton').addEventListener('click', async () => {
            const query = document.getElementById('query').value.trim();
            if (!query) return;

            // 清除欢迎消息
            const welcomeMessage = document.querySelector('.welcome-message');
            if (welcomeMessage) {
                welcomeMessage.remove();
            }

            // 添加用户消息
            addMessage(query, true);
            
            // 显示正在输入指示器
            showTypingIndicator();
            
            // 禁用发送按钮
            const sendButton = document.getElementById('sendButton');
            sendButton.disabled = true;
            sendButton.innerHTML = '<div class="loading"></div>';
            
            // 重置输入框
            textarea.value = '';
            textarea.style.height = 'auto';
            
            // 准备API请求参数
            const selectedUrl = document.getElementById('urlSelect').value;
            const stream = document.getElementById('streamCheck').checked;
            const knowledgeEnhanced = document.getElementById('knowledgeEnhanced').checked;
            
            // 如果知识增强被选中，使用增强版接口
            const finalUrl = knowledgeEnhanced ? 'http://localhost:8000/llm/chatPlus' : selectedUrl;

            const headers = {
                'Content-Type': 'application/json',
                'sessionId': document.getElementById('sessionIdInput').value || 1,
                'knowledgeBaseId': document.getElementById('knowledgeBaseIdInput').value || 1
            };

            const body = JSON.stringify({
                question: query,
                stream: stream,
                model: document.getElementById('modelSelect').value
            });

            try {
                // 发送请求
                const response = await fetch(finalUrl, {
                    method: 'POST',
                    headers: headers,
                    body: body
                });

                if (!response.ok) throw new Error('请求失败');

                // 隐藏正在输入指示器
                hideTypingIndicator();

                if (stream) {
                    // 流式响应处理
                    const reader = response.body.getReader();
                    const responseContentDiv = addMessage('', false);
                    let content = '';
                    
                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;
                        
                        const chunk = new TextDecoder().decode(value);
                        content += chunk;
                        responseContentDiv.innerHTML = marked.parse(content);
                        
                        // 应用代码高亮
                        responseContentDiv.querySelectorAll('pre code').forEach((block) => {
                            hljs.highlightElement(block);
                        });
                        
                        // 滚动到底部
                        const chatArea = document.getElementById('chatArea');
                        chatArea.scrollTop = chatArea.scrollHeight;
                    }
                } else {
                    // 非流式响应处理
                    const data = await response.json();
                    addMessage(data.data, false);
                }
            } catch (error) {
                hideTypingIndicator();
                addMessage(`请求失败：${error.message}`, false);
            } finally {
                // 恢复发送按钮
                sendButton.disabled = false;
                sendButton.innerHTML = '<i class="fa-solid fa-paper-plane"></i>';
            }
        });

        // 按 Enter 键发送消息
        textarea.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                document.getElementById('sendButton').click();
            }
        });

        // 处理知识增强选项和URL选择之间的关系
        const knowledgeEnhancedCheckbox = document.getElementById('knowledgeEnhanced');
        const urlSelect = document.getElementById('urlSelect');
        
        // 独立保存之前选择的URL，以便在关闭知识增强时恢复
        let previousUrl = urlSelect.value;
        
        // 知识增强切换时逻辑
        knowledgeEnhancedCheckbox.addEventListener('change', function() {
            if (this.checked) {
                // 记住当前URL并切换到增强接口
                previousUrl = urlSelect.value;
                urlSelect.value = 'http://localhost:8000/llm/chatPlus';
            } else {
                // 恢复到之前选择的URL
                urlSelect.value = previousUrl;
            }
        });

        // URL选择器变更时更新知识增强选项
        urlSelect.addEventListener('change', function() {
            // 记住当前选择的URL
            previousUrl = this.value;
            
            // 根据URL更新知识增强复选框
            knowledgeEnhancedCheckbox.checked = this.value === 'http://localhost:8000/llm/chatPlus';
        });
    </script>
</body>
</html>
